using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using Common;
using Common.Enum;
using Common.NotifyEvent;
using Converters;
using CustomChart;
using device;
using Microsoft.Win32;
using SExperiment;
using SProject;

namespace SWellPlate
{
    public partial class UCPlate : UserControl, IComponentConnector
    {
        public delegate void DelegateOnDeleteSampleAllEvent(object sender, EventArgs e);

        public static readonly RoutedEvent OnItemUpdateRoutedEvent = EventManager.RegisterRoutedEvent("OnItemUpdateRoutedEvent", RoutingStrategy.Bubble, typeof(EventHandler<RoutedEventArgs>), typeof(UCPlate));

        public static readonly RoutedEvent OnSelectionChangedRoutedEvent = EventManager.RegisterRoutedEvent("OnSelectionChangedRoutedEvent", RoutingStrategy.Bubble, typeof(EventHandler<RoutedEventArgs>), typeof(UCPlate));

        public static readonly DependencyProperty UseScientificProperty = DependencyProperty.Register("UseScientific", typeof(bool), typeof(UCPlate), new UIPropertyMetadata(true, OnUseScientificChanged));

        public static readonly DependencyProperty IsDecryptProperty = DependencyProperty.Register("IsDecrypt", typeof(bool), typeof(UCPlate), new UIPropertyMetadata(true));

        public static readonly DependencyProperty ModelProperty = DependencyProperty.Register("Model", typeof(string), typeof(UCPlate), new PropertyMetadata(Device.DeviceModel_96P, OnWellsChanged));

        public static readonly DependencyProperty MultiSelectProperty = DependencyProperty.Register("MultiSelect", typeof(bool), typeof(UCPlate), new UIPropertyMetadata(true));

        public static readonly DependencyProperty ColorModeProperty = DependencyProperty.Register("ColorMode", typeof(EColorMode), typeof(UCPlate), new UIPropertyMetadata(EColorMode.Channel));

        public static readonly DependencyProperty WellSelectModeProperty = DependencyProperty.Register("WellSelectMode", typeof(EWellSelectMode), typeof(UCPlate), new UIPropertyMetadata(EWellSelectMode.Sample));

        public static readonly DependencyProperty PressCtlCanSelectWellProperty = DependencyProperty.Register("PressCtlCanSelectWell", typeof(bool), typeof(UCPlate), new UIPropertyMetadata(false));

        public static readonly DependencyProperty WellDisplayModeProperty = DependencyProperty.Register("WellDisplayMode", typeof(EWellDisplayMode), typeof(UCPlate), new UIPropertyMetadata(EWellDisplayMode.ProjectName, OnWellDisplayModeChanged));

        public static readonly DependencyProperty HighLightProperty = DependencyProperty.Register("HighLight", typeof(bool), typeof(UCPlate), new UIPropertyMetadata(true));

        public static readonly DependencyProperty WellsProperty = DependencyProperty.Register("Wells", typeof(List<Well>), typeof(UCPlate), new PropertyMetadata(null, OnWellsChanged));

        public static readonly DependencyProperty SelectedProjectProperty = DependencyProperty.Register("SelectedProject", typeof(Project), typeof(UCPlate), new PropertyMetadata(null));

        public static readonly DependencyProperty SubsetProperty = DependencyProperty.Register("Subset", typeof(Subset), typeof(UCPlate), new PropertyMetadata(null, OnSubsetChanged));

        public static readonly DependencyProperty SelectedSubsetProperty = DependencyProperty.Register("SelectedSubset", typeof(Subset), typeof(UCPlate), new PropertyMetadata(null, OnSelectedSubsetChanged));

        public static readonly DependencyProperty CustomCountProperty = DependencyProperty.Register("CustomCount", typeof(int), typeof(UCPlate), new UIPropertyMetadata(0));

        private WellPlate WellPlate = new WellPlate();

        private bool isColorSettingEnable = true;

        public bool UseScientific
        {
            get
            {
                return (bool)GetValue(UseScientificProperty);
            }
            set
            {
                SetValue(UseScientificProperty, value);
            }
        }

        public bool IsDecrypt
        {
            get
            {
                return (bool)GetValue(IsDecryptProperty);
            }
            set
            {
                SetValue(IsDecryptProperty, value);
            }
        }

        public string Model
        {
            get
            {
                return (string)GetValue(ModelProperty);
            }
            set
            {
                SetValue(ModelProperty, value);
            }
        }

        public bool MultiSelect
        {
            get
            {
                return (bool)GetValue(MultiSelectProperty);
            }
            set
            {
                SetValue(MultiSelectProperty, value);
            }
        }

        public EColorMode ColorMode
        {
            get
            {
                return (EColorMode)GetValue(ColorModeProperty);
            }
            set
            {
                SetValue(ColorModeProperty, value);
            }
        }

        public EWellSelectMode WellSelectMode
        {
            get
            {
                return (EWellSelectMode)GetValue(WellSelectModeProperty);
            }
            set
            {
                SetValue(WellSelectModeProperty, value);
            }
        }

        public bool PressCtlCanSelectWell
        {
            get
            {
                return (bool)GetValue(PressCtlCanSelectWellProperty);
            }
            set
            {
                SetValue(PressCtlCanSelectWellProperty, value);
            }
        }

        public EWellDisplayMode WellDisplayMode
        {
            get
            {
                return (EWellDisplayMode)GetValue(WellDisplayModeProperty);
            }
            set
            {
                SetValue(WellDisplayModeProperty, value);
            }
        }

        public bool HighLight
        {
            get
            {
                return (bool)GetValue(HighLightProperty);
            }
            set
            {
                SetValue(HighLightProperty, value);
            }
        }

        public List<Well> Wells
        {
            get
            {
                return (List<Well>)GetValue(WellsProperty);
            }
            set
            {
                SetValue(WellsProperty, value);
            }
        }

        public Project SelectedProject
        {
            get
            {
                return (Project)GetValue(SelectedProjectProperty);
            }
            set
            {
                SetValue(SelectedProjectProperty, value);
            }
        }

        public Subset Subset
        {
            get
            {
                return (Subset)GetValue(SubsetProperty);
            }
            set
            {
                SetValue(SubsetProperty, value);
            }
        }

        public Subset SelectedSubset
        {
            get
            {
                return (Subset)GetValue(SelectedSubsetProperty);
            }
            set
            {
                SetValue(SelectedSubsetProperty, value);
            }
        }

        public int CustomCount
        {
            get
            {
                return (int)GetValue(CustomCountProperty);
            }
            set
            {
                SetValue(CustomCountProperty, value);
            }
        }

        public List<WellCell> SelectedWells
        {
            get
            {
                return WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            }
        }

        public ObservableCollection<WellCell> WellCells
        {
            get
            {
                return WellPlate.WellCells;
            }
        }

        public ObservableCollection<ChartData> WellTargets
        {
            get
            {
                return WellPlate.WellTargets;
            }
        }

        public Experiment Experiment { get; set; }

        public event RoutedEventHandler OnItemUpdate
        {
            add
            {
                AddHandler(OnItemUpdateRoutedEvent, value);
            }
            remove
            {
                RemoveHandler(OnItemUpdateRoutedEvent, value);
            }
        }

        public event RoutedEventHandler OnSelectionChanged
        {
            add
            {
                AddHandler(OnSelectionChangedRoutedEvent, value);
            }
            remove
            {
                RemoveHandler(OnSelectionChangedRoutedEvent, value);
            }
        }

        public event DelegateOnDeleteSampleAllEvent OnDeleteSampleAll;

        public void RaiseItemUpdateEvent()
        {
            RaiseEvent(new RoutedEventArgs
            {
                RoutedEvent = OnItemUpdateRoutedEvent
            });
        }

        private void RaiseSelectedWellsChanaged()
        {
            SelectSameSample();
            IList<Project> list = (from s in WellPlate.WellCells
                                   where s.IsSelected
                                   select s.Well.Project).Distinct().ToList();
            if (list.Count == 1)
            {
                SelectedProject = list[0];
            }
            else
            {
                SelectedProject = null;
            }
            RaiseEvent(new RoutedEventArgs
            {
                RoutedEvent = OnSelectionChangedRoutedEvent
            });
        }

        private static void OnUseScientificChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            UCPlate uCPlate = sender as UCPlate;
            if (uCPlate != null)
            {
                uCPlate.RefreshCellText();
            }
        }

        private static void OnWellDisplayModeChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            UCPlate uCPlate = sender as UCPlate;
            if (uCPlate != null)
            {
                uCPlate.RefreshCellText();
            }
        }

        private static void OnWellsChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            UCPlate uCPlate = sender as UCPlate;
            if (uCPlate != null && uCPlate.IsInitialized)
            {
                uCPlate.RefreshDataGridItemsSource();
            }
        }

        private static void OnSubsetChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            UCPlate uCPlate = sender as UCPlate;
            if (uCPlate != null && args.NewValue != null)
            {
                uCPlate.RefreshSubset();
            }
        }

        public void RefreshSubset()
        {
            foreach (WellCell wellCell in WellPlate.WellCells)
            {
                wellCell.IsEnabled = Subset.Wells.Contains(wellCell.Well);
            }
            RaiseSelectedWellsChanaged();
        }

        private static void OnSelectedSubsetChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            UCPlate uCPlate = sender as UCPlate;
            if (uCPlate != null && args.NewValue != null)
            {
                uCPlate.SelecteSubset(uCPlate.SelectedSubset);
            }
        }

        public UCPlate()
        {
            InitializeComponent();
            plate.OnSelectionChanged += Plate_OnSelectionChanged;
            base.SourceUpdated += UCPlate_SourceUpdated;
        }

        private void UCPlate_SourceUpdated(object sender, DataTransferEventArgs e)
        {
            Control control = e.OriginalSource as Control;
            if (control == null)
            {
                return;
            }
            WellCell wellCell = control.DataContext as WellCell;
            if (wellCell == null)
            {
                return;
            }
            List<ChartData> list = WellTargets.Where((ChartData s) => s.WellCell == wellCell).ToList();
            foreach (ChartData item in list)
            {
                item.HighLight = wellCell.HighLight;
            }
        }

        private void Plate_OnSelectionChanged(object sender, RoutedEventArgs e)
        {
            RaiseSelectedWellsChanaged();
        }

        public void ShowLegend(bool visible)
        {
            spSample.Visibility = ((!visible) ? Visibility.Collapsed : Visibility.Visible);
        }

        public void SelectAll()
        {
            foreach (WellCell wellCell in WellPlate.WellCells)
            {
                wellCell.IsSelected = wellCell.IsEnabled;
            }
            RaiseSelectedWellsChanaged();
        }

        public void SelectWell(Well well)
        {
            if (well != null)
            {
                foreach (WellCell wellCell in WellPlate.WellCells)
                {
                    wellCell.IsSelected = wellCell.Well == well || (well.Sample != null && wellCell.Well.Sample == well.Sample);
                }
            }
            RaiseSelectedWellsChanaged();
        }

        public void SelecteSubset(Subset subset)
        {
            if (subset == null)
            {
                return;
            }
            foreach (WellCell wellCell in WellPlate.WellCells)
            {
                wellCell.IsSelectedSubset = subset.Wells.Contains(wellCell.Well);
            }
        }

        public IList<Sample> GetSelectedSample()
        {
            return (from s in WellPlate.WellCells
                    where s.IsSelected && s.Well.Sample != null
                    select s.Well.Sample).Distinct().ToList();
        }

        public void SetSelectedWellProject(Project project)
        {
            int num = 1;
            if (project != null)
            {
                num = project.Target.GetTubeCount();
            }
            Sample sample = null;
            int num2 = 1;
            IList<WellCell> list = WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            if (project != null)
            {
                list = ((!project.BasicInfo.TubeSortByColumn) ? list.OrderBy((WellCell s) => s.RowIndex).ToList() : list.OrderBy((WellCell s) => s.ColumnIndex).ToList());
            }
            int num3 = list.Count - list.Count % num;
            for (int i = 0; i < num3; i++)
            {
                Well well = list[i].Well;
                if (project != null)
                {
                    if (num2 > num)
                    {
                        num2 = 1;
                    }
                    if (num2 == 1)
                    {
                        sample = new Sample(project, CustomCount);
                    }
                    sample.Wells.Add(well);
                    well.SetSample(sample, num2++);
                }
                else
                {
                    well.DeleteSmaple();
                }
            }
            while (num3 < list.Count)
            {
                Well well2 = list[num3].Well;
                if (well2 != null)
                {
                    well2.DeleteSmaple();
                    num3++;
                }
            }
            RaiseSelectedWellsChanaged();
        }

        private void RefreshDataGridItemsSource()
        {
            if (Wells == null)
            {
                return;
            }
            int row = 8;
            int column = 12;
            if (Model == Device.DeviceModel_40P)
            {
                WellPlate.RefreshWellRow(2, Wells.Where((Well s) => (s.ColumnIndex == 0 || s.ColumnIndex == 6) && s.RowIndex < 4).ToList());
            }
            else
            {
                if (Model == Device.DeviceModel_48P && ConfigReader.GetInstance().GetShowWellPlateByModel())
                {
                    column = 6;
                    row = 8;
                }
                else if (Model == Device.DeviceModel_24P)
                {
                    column = 8;
                    row = 3;
                }
                WellPlate.RefreshWellRow(column, Wells.Where((Well s) => s.ColumnIndex < column && s.RowIndex < row).ToList());
            }
            plate.SetItems(WellPlate.WellCells, row, column);
            foreach (WellCell wellCell in WellPlate.WellCells)
            {
                if (wellCell.Well.Sample != null && wellCell.Well.Targets.Count > 0)
                {
                    wellCell.Well.Targets[0].Event += SampleTargetItem_Event;
                }
                wellCell.Well.Event += Well_Event;
            }
            RefreshSampleType();
        }

        private void Well_Event(object sender, EventArgs e)
        {
            PropertyChangedEventArgsEx propertyChangedEventArgsEx = e as PropertyChangedEventArgsEx;
            if (propertyChangedEventArgsEx != null && propertyChangedEventArgsEx.PropertyName == "Sample")
            {
                Well well = sender as Well;
                if (well.Sample != null && well.Targets.Count > 0)
                {
                    well.Targets[0].Event += SampleTargetItem_Event;
                }
                RefreshSampleType();
            }
        }

        private void SampleTargetItem_Event(object sender, EventArgs e)
        {
            PropertyChangedEventArgsEx propertyChangedEventArgsEx = e as PropertyChangedEventArgsEx;
            if (propertyChangedEventArgsEx != null && propertyChangedEventArgsEx.PropertyName == "SampleType")
            {
                RefreshSampleType();
            }
        }

        public void RefreshSampleType()
        {
            List<SampleType> list = (from s in WellPlate.WellCells
                                     where s.Well.Sample != null
                                     select s.Well.Targets[0].SampleType).Distinct().ToList();
            gridUnknow.Visibility = ((!list.Contains(SampleType.Unknown)) ? Visibility.Collapsed : Visibility.Visible);
            gridStandard.Visibility = ((!list.Contains(SampleType.Standard)) ? Visibility.Collapsed : Visibility.Visible);
            gridHighPositive.Visibility = ((!list.Contains(SampleType.HighPositive)) ? Visibility.Collapsed : Visibility.Visible);
            gridLowPositive.Visibility = ((!list.Contains(SampleType.LowPositive)) ? Visibility.Collapsed : Visibility.Visible);
            gridNegative.Visibility = ((!list.Contains(SampleType.Negative)) ? Visibility.Collapsed : Visibility.Visible);
            gridNTC.Visibility = ((!list.Contains(SampleType.NTC)) ? Visibility.Collapsed : Visibility.Visible);
            gridQC.Visibility = ((!list.Contains(SampleType.QC)) ? Visibility.Collapsed : Visibility.Visible);
            gridRetestSample.Visibility = ((!list.Contains(SampleType.RetestSample)) ? Visibility.Collapsed : Visibility.Visible);
        }

        private void SelectSameSample()
        {
            if (!MultiSelect || WellSelectMode != 0 || (PressCtlCanSelectWell && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control))
            {
                return;
            }
            IList<WellCell> list = WellPlate.WellCells.Where((WellCell s) => s.IsSelected && s.Well.Sample != null).ToList();
            foreach (WellCell wellCell in list)
            {
                ObservableCollection<WellCell> wellCells = WellPlate.WellCells;
                Func<WellCell, bool> predicate = (WellCell s) => s.Well.Sample == wellCell.Well.Sample;
                foreach (WellCell item in (IEnumerable<WellCell>)wellCells.Where(predicate).ToList())
                {
                    item.IsSelected = true;
                }
            }
        }

        public void SetContextMenu_UCPatientInfoForWell()
        {
            ContextMenu contextMenu = new ContextMenu();
            MenuItem menuItem = new MenuItem();
            menuItem.Header = Utility.GetMessage("delete_sample_patientInfo");
            menuItem.Click += deleteSampleInfo_Click;
            contextMenu.Items.Add(menuItem);
            CreateMenuItemWellDisplayMode(contextMenu);
            contextMenu.Opened += menu_Opened;
            plate.ContextMenu = contextMenu;
        }

        private void menu_Opened(object sender, RoutedEventArgs e)
        {
            IList<WellCell> source = WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            int num = (from s in source
                       where s.Well.Sample != null && (s.Well.Sample.Items[0].SampleType == SampleType.RetestSample || s.Well.Sample.Items[0].SampleType == SampleType.Unknown)
                       select s.Well).ToList().Count();
            ContextMenu contextMenu = sender as ContextMenu;
            if (contextMenu == null)
            {
                return;
            }
            foreach (MenuItem item in contextMenu.Items.OfType<MenuItem>())
            {
                if (item.Header.ToString() == Utility.GetMessage("delete_sample_patientInfo") || item.Header.ToString() == Utility.GetMessage("sample_index"))
                {
                    item.IsEnabled = num > 0 && IsDecrypt;
                }
            }
        }

        public ContextMenu GetContextMenu()
        {
            return plate.ContextMenu;
        }

        private void deleteSampleInfo_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show(Utility.GetMessage("msg_delete_question"), Utility.GetMessage("Warning"), MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.No) != MessageBoxResult.Yes)
            {
                return;
            }
            IList<WellCell> list = WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            foreach (WellCell item in list)
            {
                item.Well.Sample.PatientInfo.Clear();
            }
            RaiseSelectedWellsChanaged();
            RaiseItemUpdateEvent();
        }

        public void SetContextMenu_Disable()
        {
            plate.ContextMenu = null;
        }

        private void ContextMenu_Initialized(object sender, EventArgs e)
        {
            ContextMenu contextMenu = sender as ContextMenu;
            if (contextMenu != null)
            {
                CreateMenuItemWellDisplayMode(contextMenu);
            }
        }

        public void CreateMenuItemWellDisplayMode(ContextMenu menu)
        {
            menu.Items.Add(new Separator());
            MenuItem menuItem = new MenuItem();
            menuItem = new MenuItem();
            menuItem.SetResourceReference(HeaderedItemsControl.HeaderProperty, "well_display_text");
            MenuItem menuItem2 = new MenuItem();
            menuItem2.IsCheckable = true;
            menuItem2.SetResourceReference(HeaderedItemsControl.HeaderProperty, "project_name");
            menuItem2.SetBinding(MenuItem.IsCheckedProperty, new Binding("WellDisplayMode")
            {
                Source = this,
                Mode = BindingMode.TwoWay,
                Converter = new EnumBooleanConverter(),
                ConverterParameter = EWellDisplayMode.ProjectName,
                NotifyOnSourceUpdated = true,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });
            menuItem.Items.Add(menuItem2);
            menuItem2 = new MenuItem();
            menuItem2.IsCheckable = true;
            menuItem2.SetResourceReference(HeaderedItemsControl.HeaderProperty, "patient_name");
            menuItem2.SetBinding(MenuItem.IsCheckedProperty, new Binding("WellDisplayMode")
            {
                Source = this,
                Mode = BindingMode.TwoWay,
                Converter = new EnumBooleanConverter(),
                ConverterParameter = EWellDisplayMode.PatientName,
                NotifyOnSourceUpdated = true,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });
            menuItem.Items.Add(menuItem2);
            menuItem2 = new MenuItem();
            menuItem2.IsCheckable = true;
            menuItem2.SetResourceReference(HeaderedItemsControl.HeaderProperty, "sample_index");
            menuItem2.SetBinding(MenuItem.IsCheckedProperty, new Binding("WellDisplayMode")
            {
                Source = this,
                Mode = BindingMode.TwoWay,
                Converter = new EnumBooleanConverter(),
                ConverterParameter = EWellDisplayMode.SampleID,
                NotifyOnSourceUpdated = true,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });
            menuItem.Items.Add(menuItem2);
            menuItem2 = new MenuItem();
            menuItem2.IsCheckable = true;
            menuItem2.SetResourceReference(HeaderedItemsControl.HeaderProperty, "tube_name");
            menuItem2.SetBinding(MenuItem.IsCheckedProperty, new Binding("WellDisplayMode")
            {
                Source = this,
                Mode = BindingMode.TwoWay,
                Converter = new EnumBooleanConverter(),
                ConverterParameter = EWellDisplayMode.TubeName,
                NotifyOnSourceUpdated = true,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });
            menuItem.Items.Add(menuItem2);
            menuItem2 = new MenuItem();
            menuItem2.IsCheckable = true;
            menuItem2.SetResourceReference(HeaderedItemsControl.HeaderProperty, "sample_name");
            menuItem2.SetBinding(MenuItem.IsCheckedProperty, new Binding("WellDisplayMode")
            {
                Source = this,
                Mode = BindingMode.TwoWay,
                Converter = new EnumBooleanConverter(),
                ConverterParameter = EWellDisplayMode.SampleName,
                NotifyOnSourceUpdated = true,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });
            menuItem.Items.Add(menuItem2);
            menu.Items.Add(menuItem);
        }

        public void SetMenuItemColorSettingEnable(bool enable)
        {
            isColorSettingEnable = enable;
        }

        private void dataGridContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            menuItemBadWell.Checked -= menuItemBadWell_Checked;
            menuItemBadWell.Unchecked -= menuItemBadWell_Unchecked;
            IList<WellCell> list = WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            List<Project> list2 = (from s in list
                                   where s.Well.Project != null
                                   select s.Well.Project).ToList();
            menuItemColorSetting.IsEnabled = isColorSettingEnable && ColorMode != EColorMode.Result && list2.Count > 0 && IsDecrypt;
            menuItemDeleteWell.IsEnabled = list2.Count > 0 && IsDecrypt;
            menuItemWellEdit.IsEnabled = Experiment != null && IsDecrypt;
            int num = list.Where((WellCell s) => s.Well.Sample != null).Count();
            menuItemBadWell.IsChecked = list.Count > 0 && num > 0 && list.Where((WellCell s) => s.Well.IsInValid).Count() == num;
            menuItemBadWell.IsEnabled = list.Count > 0 && num > 0 && IsDecrypt;
            menuItemBadWell.Checked += menuItemBadWell_Checked;
            menuItemBadWell.Unchecked += menuItemBadWell_Unchecked;
        }

        private void menuItemBadWell_Checked(object sender, RoutedEventArgs e)
        {
            IList<WellCell> list = WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            foreach (WellCell item in list)
            {
                item.Well.IsInValid = true;
            }
            RaiseItemUpdateEvent();
        }

        private void menuItemBadWell_Unchecked(object sender, RoutedEventArgs e)
        {
            IList<WellCell> list = WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            foreach (WellCell item in list)
            {
                item.Well.IsInValid = false;
            }
            RaiseItemUpdateEvent();
        }

        private bool isMultiTubeAllSelected()
        {
            bool result = true;
            IList<WellCell> source = WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            foreach (Well item in from s in source
                                  where s.Well.MultiTubeID > 0
                                  select s.Well)
            {
                foreach (Well insideWell in item.Sample.Wells)
                {
                    Func<WellCell, bool> predicate = (WellCell s) => s.RowIndex == insideWell.RowIndex && s.ColumnIndex == insideWell.ColumnIndex;
                    if (source.Where(predicate).Count() == 0)
                    {
                        result = false;
                    }
                }
            }
            return result;
        }

        private void WellEdit_Click(object sender, RoutedEventArgs e)
        {
            if (!isMultiTubeAllSelected())
            {
                MessageBox.Show(Utility.GetMessage("msg_please_select_all_multitube"), Utility.GetMessage("Warning"), MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }
            WellEditWindow wellEditWindow = new WellEditWindow(SelectedWells);
            wellEditWindow.Owner = Utility.GetMainWindow();
            wellEditWindow.IniProjectCombox(Experiment, SelectedProject);
            if (wellEditWindow.ShowDialog() == true)
            {
                SetSelectedWellProject(wellEditWindow.ComboxSelectedProject);
                wellEditWindow.SetResult();
                RaiseSelectedWellsChanaged();
                wellEditWindow.Close();
                RaiseItemUpdateEvent();
            }
        }

        private void WellColorSetting_Click(object sender, RoutedEventArgs e)
        {
            CurveStyleSettingWindow curveStyleSettingWindow = new CurveStyleSettingWindow();
            curveStyleSettingWindow.Owner = Utility.GetMainWindow();
            curveStyleSettingWindow.ShowTargets = true;
            IList<WellCell> source = WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            List<List<string>> list = source.Select((WellCell s) => s.Well.Targets.Select((SampleTargetItem x) => x.TargetName).ToList()).ToList();
            WellTargets.Where((ChartData s) => s.WellCell.IsSelected && s.SampleTargetItem.HasCustomColor(ColorMode)).Count();
            List<Color> list2 = (from s in WellTargets
                                 where s.WellCell.IsSelected
                                 select s.GetChartDataColor(ColorMode)).Distinct().ToList();
            if (list2.Count == 1)
            {
                curveStyleSettingWindow.Color = list2[0];
            }
            else
            {
                curveStyleSettingWindow.Color = Colors.Transparent;
            }
            WellTargets.Where((ChartData s) => s.WellCell.IsSelected && s.SampleTargetItem.HasCustomLinePointStyle(ColorMode)).Count();
            List<ESeriesType> list3 = (from s in WellTargets
                                       where s.WellCell.IsSelected
                                       select s.GetChartDataLinePointStyle(ColorMode)).Distinct().ToList();
            if (list3.Count == 1)
            {
                curveStyleSettingWindow.Symbol = list3[0];
            }
            else
            {
                curveStyleSettingWindow.Symbol = ESeriesType.Null;
            }
            List<string> list4 = new List<string>();
            foreach (List<string> item in list)
            {
                foreach (string item2 in item)
                {
                    if (!list4.Contains(item2))
                    {
                        list4.Add(item2);
                    }
                }
            }
            curveStyleSettingWindow.SetTargetNames(list4);
            curveStyleSettingWindow.OnApply += window_OnApply;
            bool flag = curveStyleSettingWindow.ShowDialog() == true;
        }

        private void window_OnApply(object sender, EventArgs e)
        {
            CurveStyleSettingWindow curveStyleSettingWindow = sender as CurveStyleSettingWindow;
            if (curveStyleSettingWindow == null)
            {
                return;
            }
            bool flag = false;
            bool flag2 = false;
            IList<WellCell> list = WellPlate.WellCells.Where((WellCell s) => s.IsSelected).ToList();
            List<Color> list2 = (from s in WellTargets
                                 where s.WellCell.IsSelected
                                 select s.GetChartDataColor(ColorMode)).Distinct().ToList();
            if (list2.Count == 1)
            {
                flag2 = true;
            }
            if (!curveStyleSettingWindow.IsAllTarget())
            {
                flag = true;
            }
            foreach (WellCell item in list)
            {
                foreach (SampleTargetItem target in item.Well.Targets)
                {
                    if (flag)
                    {
                        if (target.TargetName.Equals(curveStyleSettingWindow.TargetName))
                        {
                            if (flag2)
                            {
                                target.AddColor(ColorMode, curveStyleSettingWindow.Color);
                            }
                            else if (curveStyleSettingWindow.Color != Colors.Transparent)
                            {
                                target.AddColor(ColorMode, curveStyleSettingWindow.Color);
                            }
                            if (curveStyleSettingWindow.Symbol != ESeriesType.Null)
                            {
                                target.AddLinePointStyle(ColorMode, curveStyleSettingWindow.Symbol);
                            }
                        }
                    }
                    else
                    {
                        if (flag2)
                        {
                            target.AddColor(ColorMode, curveStyleSettingWindow.Color);
                        }
                        else if (curveStyleSettingWindow.Color != Colors.Transparent)
                        {
                            target.AddColor(ColorMode, curveStyleSettingWindow.Color);
                        }
                        if (curveStyleSettingWindow.Symbol != ESeriesType.Null)
                        {
                            target.AddLinePointStyle(ColorMode, curveStyleSettingWindow.Symbol);
                        }
                    }
                }
            }
            RaiseItemUpdateEvent();
        }

        private void WellSaveImage_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Utility.GetMyDocumentFolder();
            saveFileDialog.Filter = string.Format("{1}{0}|*.{1}|{2}{0}|*.{2}|{3}{0}|*.{3}", Utility.GetMessage("File"), "png", "jpg", "bmp");
            if (saveFileDialog.ShowDialog() == true)
            {
                switch (saveFileDialog.FilterIndex)
                {
                    case 1:
                        Utility.SaveAsImagePng(saveFileDialog.FileName, this);
                        break;
                    case 2:
                        Utility.SaveAsImageJpg(saveFileDialog.FileName, this);
                        break;
                    case 3:
                        Utility.SaveAsImagebmp(saveFileDialog.FileName, this);
                        break;
                }
                MessageBox.Show(Utility.GetMessage("msg_saveimage_sussess"));
            }
        }

        private void DeleteWell_Click(object sender, RoutedEventArgs e)
        {
            DeleteWell_Execute();
        }

        public void DeleteWell_Execute()
        {
            if (!isMultiTubeAllSelected())
            {
                MessageBox.Show(Utility.GetMessage("msg_please_select_all_multitube"), Utility.GetMessage("Warning"), MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            else if (MessageBox.Show(Utility.GetMessage("msg_deletewell"), Utility.GetMessage("Warning"), MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.No) == MessageBoxResult.Yes)
            {
                SetSelectedWellProject(null);
                if (WellPlate.WellCells.Where((WellCell s) => s.Well.Project != null).Distinct().ToList()
                    .Count == 0 && this.OnDeleteSampleAll != null)
                {
                    this.OnDeleteSampleAll(this, new EventArgs());
                }
                RaiseItemUpdateEvent();
            }
        }

        public void RefreshCellText()
        {
            foreach (WellCell wellCell in WellPlate.WellCells)
            {
                wellCell.UseScientific = UseScientific;
                wellCell.WellDisplayMode = WellDisplayMode;
                wellCell.RefreshText();
            }
        }

        public void RefreshSelectedWells(bool forceRefresh = false)
        {
            RaiseSelectedWellsChanaged();
        }

        public void RefreshHeight()
        {
        }
    }
}
